const request = require('../../utils/request');
const buildUrl = request.buildUrl || ((url) => url);

Page({
  data: {
    pendingTotal: '0.00',
    pendingCount: 0,
    lastPaidTime: '',
    pendingOrders: [],
    paidOrders: []
  },

  onLoad() {
    this.loadWalletData();
  },

  onShow() {
    this.loadWalletData();
  },

  getUserId() {
    const app = getApp();
    return app.globalData.userId || wx.getStorageSync('userId');
  },

  async loadWalletData() {
    const userId = this.getUserId();
    if (!userId) {
      wx.reLaunch({ url: '/pages/login/login' });
      return;
    }

    try {
      const res = await request({
        url: `/api/orders/user/${userId}`,
        method: 'GET'
      });

      let orders = [];
      if (res.success && res.data) {
        if (Array.isArray(res.data)) {
          orders = res.data;
        } else if (Array.isArray(res.data.orders)) {
          orders = res.data.orders;
        } else if (Array.isArray(res.data.list)) {
          orders = res.data.list;
        }
      }

      const normalized = orders.map(o => ({
        id: o.id,
        status: o.status,
        amount: Number(o.final_fee || o.suggested_fee || o.amount || 0).toFixed(2),
        deliveryAddress: o.delivery_address || o.deliveryAddress || '',
        createdAt: this.formatTime(o.created_at || o.createdAt),
        paidAt: this.formatTime(o.paid_at || o.completed_at || '')
      }));

      const pendingOrders = normalized.filter(o => o.status === 4); // 4: 送达中、待支付（依你实际状态调整）
      const paidOrders = normalized
        .filter(o => [5].includes(o.status))
        .sort((a, b) => (b.paidAtRaw || 0) - (a.paidAtRaw || 0));

      const pendingTotalRaw = pendingOrders.reduce((sum, o) => sum + Number(o.amount || 0), 0);
      const lastPaid = paidOrders.length > 0 ? paidOrders[0].paidAt : '';

      this.setData({
        pendingOrders,
        paidOrders,
        pendingCount: pendingOrders.length,
        pendingTotal: pendingTotalRaw.toFixed(2),
        lastPaidTime: lastPaid
      });
    } catch (e) {
      console.error('加载钱包数据失败:', e);
      wx.showToast({ title: '钱包数据加载失败', icon: 'none' });
    }
  },

  formatTime(t) {
    if (!t) return '';
    const d = new Date(t);
    if (Number.isNaN(d.getTime())) return '';
    const m = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    const hh = String(d.getHours()).padStart(2, '0');
    const mm = String(d.getMinutes()).padStart(2, '0');
    return `${m}-${day} ${hh}:${mm}`;
  },

  scrollToPending() {
    wx.pageScrollTo({ selector: '#pending-section', duration: 300 });
  },

  scrollToHistory() {
    wx.pageScrollTo({ selector: '#history-section', duration: 300 });
  },

  showPayInfo() {
    wx.showModal({
      title: '支付说明',
      content: '当前为开发测试环境，支付采用模拟模式，不会真实扣除资金。',
      showCancel: false
    });
  },

  goPay(e) {
    const orderId = e.currentTarget.dataset.orderId;
    const amount = e.currentTarget.dataset.amount;
    if (!orderId) return;
    wx.navigateTo({
      url: `/pages/payment/payment?orderId=${orderId}&amount=${amount}`
    });
  }
});
